package com.javatest.futuretest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 *
 * @author liuziyang
 * @date 2021/2/19 23:12
 */
public class CompletableFutureExample {
    private static final Logger log = LoggerFactory.getLogger(CompletableFutureExample.class);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 1. runAsync无返回值
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
            log.info("runAsynce运行在一个单独的线程当中");
        });

        future.get();

        // 2. supplyAsync有返回值
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
            log.info("supplyAsync运行在一个单独的线程当中");
            return "我有返回值";
        });

        log.info(future2.get());

        // 3.通过传入回调函数，在Future 结束时自动调用该回调函数
        CompletableFuture<String> comboText = CompletableFuture.supplyAsync(() -> {
            //可以注释掉做快速返回 start
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
            log.info("???");
            //可以注释掉做快速返回 end
            return "赞";
        })
                .thenApply(first -> {
                    log.info("在看");
                    return first + ", 在看";
                })
                .thenApply(second -> second + ", 转发");

        log.info("三连有没有？");
        log.info(comboText.get());
    }
}
